import Vue from 'vue';
import Axios from 'axios';
import AxiosConfig from './axios.config';
import App from '../main.js';
var fileUploadConfig = {
  baseURL: '',
  timeout: 50000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'LanguageType': window.sessionStorage.getItem('lang') ? window.sessionStorage.getItem('lang') : 'zh'
  }
};
Axios.interceptors.request.use(function(config) {
  return config;
}, function(error) {
  return Promise.reject(error);
});

Axios.interceptors.response.use(function(response) {
  return response;
}, function(error) {
  return Promise.reject(error);
});
/**
 * Get 方法获取参数时，需拼接，
 * @param {*} parmas 
 * GET方法传入对象，然后拼接
 */
let _getParmas = (parmas) => {
  let _parmas = '';
  for (let item in parmas) {
    _parmas += item + '=' + parmas[item] + '&';
  };
  return '?' + _parmas.substr(0, _parmas.length - 1);
};
class Ajax {
  static Post(url, parmas, cancelToken) {
    return new Promise((resolve, reject) => {
      Axios.post(url, parmas, { cancelToken, ...AxiosConfig }).then((res) => {
        resolve(Ajax.AjaxHandlerFunction(res.data, resolve, reject));
      }).catch((error) => {
        reject(error);
      });
    });
  }
  static Get(url, parmas) {
    return new Promise((resolve, reject) => {
      Axios.get(url + _getParmas(parmas), AxiosConfig).then((res) => {
        resolve(Ajax.AjaxHandlerFunction(res.data, resolve, reject));
      }).catch((error) => {
        reject(error);
      });
    });
  }
  static All(functionArr, callbackFn) {
    Axios.all(functionArr)
      .then(Axios.spread(function() {
        callbackFn(...arguments);
      }));
  }
  static upLoadFile(url, parmas) {
    return new Promise((resolve, reject) => {
      Axios.post(url, parmas, fileUploadConfig).then((res) => {
        resolve(Ajax.AjaxHandlerFunction(res.data, resolve, reject));
      }).catch((error) => {
        reject(error);
      });
    });
  }
  static AjaxHandlerFunction(data, resolve, reject) {
    let _data = typeof data == 'string' ? JSON.parse(data) : data;
    switch (_data.code.toString()) {
      case '100':
        // 成功返回
        let responseData = _data.data ? _data.data : _data.list ? _data.list : _data.imgResult ? _data.imgResult : _data.sumrmb;
        resolve(responseData);
        break;
      case '200':
        // App.$Modal.error({
        //   title: App.$t('modals.WarmPrompt'),
        //   content: '<p>' + _data.desc + '</p>'
        // });
        reject(_data.desc);
        // 校验出错
        break;
      case '301':
        resolve({
          errorTip: _data.desc
        });
        break;
      default:
        reject(_data.desc);
        break;
    }
  }
};
export {
  Ajax
};